package it.trekker.gps.service;

import it.trekker.db.Excursion;
import it.trekker.db.ExcursionDAO;
import it.trekker.db.ExcursionCoordinate;
import it.trekker.db.ExcursionCoordinateDAO;
import android.content.Context;
import android.location.Location;
import android.location.LocationProvider;
import android.util.Log;

public class GPSDataCollector implements IGPSListener {

	private static final String TAG = GPSDataCollector.class.getSimpleName();
	
	private Excursion excursion = null;
	private ExcursionDAO excursionDAO = null;
	private ExcursionCoordinateDAO gpsCoordinateDAO = null;
	
	

	public GPSDataCollector(Context ctx) {
		Log.i(TAG, "Start");
		
		excursionDAO = new ExcursionDAO(ctx);
		gpsCoordinateDAO = new ExcursionCoordinateDAO(ctx);
	}
	
	
	public int startDataCollecting(String excursionName) {
		Log.i(TAG, "Start data collecting");
		
		excursionDAO.open();
		excursion = new Excursion(excursionName);
		excursion.setId(excursionDAO.insertExcursion(excursion));
		excursionDAO.close();
		
		gpsCoordinateDAO.open();
		
		return excursion.getId();
	}
	
	public void stopDataCollecting() {
		Log.i(TAG, "Stop data collecting");

		gpsCoordinateDAO.close();
	}

	@Override
	public void onLocationChanged(Location location) {
		ExcursionCoordinate coord = new ExcursionCoordinate(location);
		coord.setExcursionId(excursion.getId());
		gpsCoordinateDAO.insertGPSCoordinate(coord);
	}

	@Override
	public void onProviderDisabled() {
		Log.i(TAG, "On provider disabled");
		gpsCoordinateDAO.close();
	}

	@Override
	public void onProviderEnabled() {
		Log.i(TAG, "On provider enabled");
		gpsCoordinateDAO.open();
	}

	@Override
	public void onStatusChanged(int status) {
		Log.i(TAG, "On status changed: " + status);
		switch(status) {
			case LocationProvider.OUT_OF_SERVICE:
			case LocationProvider.TEMPORARILY_UNAVAILABLE:
//				gpsCoordinateDAO.close();
				break;
	
			case LocationProvider.AVAILABLE:
				gpsCoordinateDAO.open();
		}
	}
	
}
